<?php

namespace Admin\Controller;

use Think\Controller;

class AdminController extends BaseController
{

    public function test()
    {
        $list = M('agent')->select();
        for ($i = 0; $i < count($list); $i++) {
            //M('agent')->where("id = {$list[$i]['id']}")->setField('password',md5('123456'));
        }
    }

    public function adminlist()
    {

        $u = $_SERVER['REQUEST_URI'];
        $url = substr($u, (strpos($u, '=') + 1), (strlen($u) - strpos($u, '=') - 6));
        $lis = explode('/', $url);
        $mmp['controller'] = $lis[2];
        $mmp['function'] = $lis[3];
        $res = M('nav')->where($mmp)->getField("id");
        $role_id = $_SESSION['adminster']['role_id'];
        if (!$role_id == 0) {
            $path = M('access')->where("role_id = {$role_id}")->getField("nav_id");
            $pathlist = explode('#', $path);
            if (!in_array($res, $pathlist)) {
                $this->error('没有权限!', U('Index/main'), 1);
                return false;
            }
        }

        $Model = D('admin');
        $count = $Model->count();
        $page = new \Think\Page($count, 10);
        $show = $page->show();
        $list = $Model->field('a.*,r.role_name')->limit($page->firstRow . ',' . $page->listRows)->order("id ASC")
            ->alias('a')
            ->join('LEFT JOIN __ROLE__ r ON r.id = a.role_id')
            ->select();
        $this->assign(array(
            'list' => $list,
            'show' => $show
        ));
        $this->display();
    }

    //前端权限页面
    public function potence()
    {
        $id = I('id');
        $ret = M('admin')->where("id = {$id}")->find();
        $this->assign('info', $ret);
        $this->display();
    }

    //前端权限方法
    public function b_potence()
    {
        $id = I('id');
        $data = I('module');
        if (in_array('wap', $data)) {
            $map['is_wap'] = 1;
        } else {
            $map['is_wap'] = 0;
        }
        if (in_array('wab', $data)) {
            $map['is_wab'] = 1;
        } else {
            $map['is_wab'] = 0;
        }
        $ret = M('admin')->where("id = {$id}")->save($map);
        if ($ret) {
            $this->success('添加权限成功！');
        } else {
            $this->error('添加权限失败！');
        }
    }

    public function rolelist()
    {

        $u = $_SERVER['REQUEST_URI'];
        $url = substr($u, (strpos($u, '=') + 1), (strlen($u) - strpos($u, '=') - 6));
        $lis = explode('/', $url);
        $mmp['controller'] = $lis[2];
        $mmp['function'] = $lis[3];
        $res = M('nav')->where($mmp)->getField("id");
        $role_id = $_SESSION['adminster']['role_id'];
        if (!$role_id == 0) {
            $path = M('access')->where("role_id = " . $role_id)->getField("nav_id");
            $pathlist = explode('#', $path);
            if (!in_array($res, $pathlist)) {
                $this->error('没有权限!', U('Index/main'), 1);
                return false;
            }
        }

        $Model = D('role');
        $count = $Model->where('status = %d', 1)->count();
        $page = new \Think\Page($count, 10);
        $show = $page->show();
        $list = $Model->where('status = %d', 1)->limit($page->firstRow . ',' . $page->listRows)->order("id ASC")->select();
        $this->assign(array(
            'list' => $list,
            'show' => $show
        ));
        $this->display();
    }

    public function agentlist()
    {

        $admin = session('admin');
        if ($admin['role_id'] != 0) {
            $map['agent_up'] = $admin['id'];
        }

        $Model = D('agent');
        $count = $Model->where($map)->count();
        $page = new \Think\Page($count, 10);
        $show = $page->show();
        $list = $Model->where($map)->limit($page->firstRow . ',' . $page->listRows)->select();

        for ($i = 0; $i < count($list); $i++) {
            $info = M('agent')->where("id = {$list[$i]['agent_up']}")->find();
            $list[$i]['agent_up_username'] = $info['username'];
        }

        $this->assign(array(
            'list' => $list,
            'show' => $show
        ));
        $this->display();
    }

    public function addadmin()
    {
        $Model = D('admin');
        if (IS_POST) {
            if (!IS_AJAX) {
                $this->error('提交方式不正确！');
            } else {
                $data['username'] = I('username');
                $data['password'] = md5(I('password'));
                $data['role_id'] = I('role_id');
                $data['status'] = 1;
                $data['create_time'] = time();
                if (!$data['username'] || !$data['password'] ) {
                    $this->error('用户名、密码不能为空！');
                    return false;
                }


                if ($data['role_id'] == 0) {
                    $this->error('非法操作！');
                    return false;
                }

                if ($data['username']) {
                    $mpp['username']=$data['username'];
                    $ret = M('admin')->where($mpp)->find();
                    if (!$ret) {
                        if ($data) {
							$data['email'] = '';
							$data['login_error_time'] = '';
							$data['last_ip'] = '';
							$data['last_time'] = '';
							$data['ticket'] = '';
							$data['role_type'] = '2';

                            $res = $Model->add($data);
                            if ($res) {
                                $this->success('添加成功！', U('Admin/Admin/adminlist'), 1);
                            } else {
                                $this->error('添加失败');
                            }
                        }
                    }else{
                        $this->error('用户名已存在！');
                    }
                }
            }
        } else {
            $rolelist = D('role')->where('status = %d and type = %d', 1, 0)->select();
            $this->assign(array(
                'rolelist' => $rolelist
            ));
            $this->display();
        }
    }

    public function addrole()
    {

        $Model = D('role');
        if (IS_POST) {
            if (!IS_AJAX) {
                $this->error('提交方式不正确！');
            } else {
                $data['role_name'] = I('role_name');
                $data['type'] = (I('type'));
                $data['status'] = 1;
                if ($data) {
                    $res = $Model->add($data);
                    if ($res) {
                        $this->success('添加成功！', U('Admin/Admin/rolelist'), 1);
                    } else {
                        $this->error('添加失败');
                    }
                }
            }
        } else {
            $this->display();
        }
    }

    public function addagent()
    {

        $Model = D('agent');
        $admin = session('adminster');
        if (IS_POST) {
            if (!IS_AJAX) {
                $this->error('提交方式不正确！');
            } else {
                if ($admin['role_id'] == 0) {
                    $data['agent_rank'] = I('agent_rank');
                    $data['role_id'] = I('role_id');
                    $data['agent_up'] = I('agent_up');
                } else {
                    $data['agent_rank'] = 2;
                    $data['role_id'] = 12;
                    $data['agent_up'] = $admin['id'];
                }
                $data['username'] = I('username');
                $data['nickname'] = I('nickname');
                $data['password'] = md5(I('password'));


                if ($data) {
                    $res = $Model->add($data);
                    if ($res) {
                        $url = C('WEB_URL') . '/Home/index?tid=' . $res;
                        $img = qrcode($url);
                        if ($img) {
                            $data['erweima'] = $img;
                            D('agent')->where('id = %d', $res)->save($data);
                        }
                        $this->success('添加成功！', U('Admin/Admin/agentlist'), 1);
                    } else {
                        $this->error('添加失败');
                    }
                }
            }
        } else {
            $rolelist = D('role')->where('status = %d and type = %d', 1, 1)->select();
            $this->assign(array(
                'rolelist' => $rolelist
            ));
            $this->assign('agent_list', M('agent')->where("agent_rank=1")->select());
            $this->display();
        }
    }

    public function editadmin()
    {

        $id = I('id');
        $Model = D('admin');
        $info = $Model->where("id = $id")->find();
        if (IS_POST) {
            if (!IS_AJAX) {
                $this->error('提交方式不正确！');
            } else {

                $data['username'] = I('username');
                $data['role_id'] = I('role_id');
                $data['phone'] = I('phone');

                if ($info['role_id'] == 0) {
                    $data['role_id'] = 0;
                } else {
                    if ($data['role_id'] == 0) {
                        $this->error('非法操作！');
                    }
                }

                if ($data) {
                    $res = $Model->where("id = $id")->save($data);
                    if ($res !== false) {
                        $this->success('编辑成功！', U('Admin/Admin/adminlist'), 1);
                    } else {
                        $this->error('编辑失败');
                    }
                }
            }
        } else {
            $rolelist = D('role')->where('status = %d and type = %d', 1, 0)->select();
            $this->assign(array(
                'info' => $info,
                'rolelist' => $rolelist
            ));
            $this->display();
        }
    }

    public function editrole()
    {

        $id = I('id');
        $Model = D('role');
        if (IS_POST) {
            if (!IS_AJAX) {
                $this->error('提交方式不正确！');
            } else {

                $data['role_name'] = I('role_name');
                $data['type'] = I('type');

                if ($data) {
                    $res = $Model->where("id = $id")->save($data);
                    if ($res) {
                        $this->success('编辑成功！', U('Admin/Admin/rolelist'), 1);
                    } else {
                        $this->error('编辑失败');
                    }
                }
            }
        } else {
            $info = $Model->where("id = $id")->find();
            $this->assign(array(
                'info' => $info
            ));
            $this->display();
        }
    }

    public function editagent()
    {

        $id = I('id');
        $Model = D('agent');
        if (IS_POST) {
            if (!IS_AJAX) {
                $this->error('提交方式不正确！');
            } else {

                $data['password'] = md5(I('password'));

                if ($data) {
                    $res = $Model->where("id = $id")->save($data);
                    if ($res) {
                        $this->success('编辑成功！', U('Admin/Admin/agentlist'), 1);
                    } else {
                        $this->error('编辑失败');
                    }
                }
            }
        } else {
            $info = M('agent')->where("id = $id")->find();

            if ($_SESSION['adminster']['role_id'] != 0) {
                if ($_SESSION['adminster']['id'] != $info['agent_up']) {
                    $this->error('无权操作！');
                }
            }

            $rolelist = D('role')->where('status = %d and type = %d', 1, 1)->select();
            $this->assign(array(
                'info' => $info,
                'rolelist' => $rolelist
            ));
            $this->display();
        }
    }

    public function deleteadmin()
    {

		$id = I('id');
		$Model = D('admin');
		$info = $Model->find($id);

    	if ($_SESSION['adminster']['username']!='admin' && $info['role_id'] == 0){
			$this->error('超级管理员禁止删除');
		}

		$operation = $Model->delete($id);

		if ($operation) {
			$this->success('删除成功！', U('Admin/Admin/adminlist'), 1);
		} else {
			$this->error('删除失败');
		}

    }

    public function deleterole()
    {

        $id = I('id');
        $Model = D('role');
        $info1 = D('admin')->where(array('role_id' => $id))->find();
//        $info2 = D('agent')->where(array('role_id' => $id))->find();
        if ($info1) {
            $this->error('角色已应用，禁止删除');
        } else {
            $result = $Model->delete($id);
            if ($result) {
                D('access')->where(array('role_id' => $id))->delete();
                $this->success('删除成功！', U('Admin/Admin/rolelist'), 1);
            } else {
                $this->error('删除失败');
            }
        }
    }

    public function deleteagent()
    {

        $id = I('id');
        $Model = D('agent');

        $info = M('agent')->where("id = $id")->find();
        if ($_SESSION['adminster']['role_id'] != 0) {
            if ($_SESSION['adminster']['id'] != $info['agent_up']) {
                $this->error('无权操作！');
            }
        }

        $result = $Model->delete($id);
        if ($result) {
            $this->success('删除成功！', U('Admin/Admin/agentlist'), 1);
        } else {
            $this->error('删除失败');
        }
    }

    public function access()
    {

        $id = I('id');
        $accessModel = D('access');
        $navModel = D('nav');
        if (IS_POST) {
            if (!IS_AJAX) {
                $this->error('提交方式不正确！');
            } else {
                $getrule = I('rule');
                $accessModel->where(array('role_id' => $id))->delete();
                if (empty($getrule)) {
                    $this->error('请选择权限！');
                }
                $data['role_id'] = $id;
                $data['nav_id'] = '1#51#73#52#' . implode("#", $getrule);

                if ($data) {
                    $res = $accessModel->add($data);
                    if ($res) {
                        $this->success('修改成功！', U('Admin/Admin/rolelist'), 1);
                    } else {
                        $this->error('修改失败');
                    }
                }

            }
        } else {
            $accessinfo = $accessModel->where('role_id = ' . $id . '')->field('nav_id')->find();
            $ids = '#' . $accessinfo['nav_id'] . '#';
            $role_type = D('role')->where('id = %d', $id)->getField('type');
            if ($role_type == 1) {
                $navlist = $navModel->where('type = %d', 1)->select();
            } else {
                $navlist = $navModel->select();
            }
            foreach ($navlist as $key => $value) {
                if ($value['controller'] == 'index' && $value['function'] == 'index') {
                    unset($navlist[$key]);
                }
            }
            $this->assign(array(
                'navlist' => $navlist,
                'group' => $ids,
                'role_id' => $id
            ));
            $this->display();
        }
    }


    public function erweima()
    {

        $id = I('id');
        $url = C('WEB_URL') . '/Home/index?tid=' . $id;
        $img = qrcode($url);
        if ($img) {
            $data['erweima'] = $img;
            $res = D('agent')->where('id = %d', $id)->save($data);
            if ($res) {
                $this->success('二维码生成成功！', U('Admin/Admin/agentlist'), 1);
            } else {
                $this->error('二维码生成失败');
            }
        };
    }


    public function xiajia()
    {

        $id = I('id');
        $nickname = I('nickname');
        if ($nickname) {
            $member = M('user');
            $count = $member->where("nickname like '%{$nickname}%' and t_id = {$id}")->count();
            $page = new \Think\Page($count, 10);
            $show = $page->show();
            $list = $member->where("nickname like '%{$nickname}%' and t_id = {$id}")->limit($page->firstRow . ',' . $page->listRows)->order("id ASC")->select();
        } else {
            $member = M('user');
            $count = $member->where('t_id = %d', $id)->count();
            $page = new \Think\Page($count, 10);
            $show = $page->show();
            $list = $member->where('t_id = %d', $id)->limit($page->firstRow . ',' . $page->listRows)->order("id ASC")->select();
        }
        foreach ($list as $key => $value) {
            $list[$key]['add_point'] = D('integral')->where('uid = %d and type = %d', $value['id'], 1)->getField('points');
            $list[$key]['del_point'] = D('integral')->where('uid = %d and type = %d', $value['id'], 0)->getField('points');
            $list[$key]['income'] = D('order')->where('userid = %d', $value['id'])->sum('add_points');
            $list[$key]['expense'] = D('order')->where('userid = %d', $value['id'])->sum('del_points');
            $list[$key]['user_agent'] = unserialize($value['user_agent'])['device'] . '/' . unserialize($value['user_agent'])['name'] . '(' . unserialize($value['user_agent'])['version'] . ')';
        }

        $this->assign('show', $show);
        $this->assign('list', $list);
        $this->assign('id', $id);
        $this->display();
    }

}